import { acceptHMRUpdate, defineStore } from 'pinia'
import { store } from '../index'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { decodeAES, encodeAES } from '@/utils/aesRsa'
import { systemConfigEnum } from '@/enums/systemConfigEnums'

export const useAppStore = defineStore('app', () => {
  const { wsLocal } = useCache()
  const { variables } = useDesign()
  // 系统配置弹窗显示隐藏
  const showSetting = ref(false)
  // 计算顶部固定的高度，使用固钉组件时，需要根据当前布局形态，计算固钉距离顶部高度
  const affixTop = ref(0)
  // 页面加载状态
  const pageLoading = ref(false)
  // 系统配置相关参数
  const systemConfig = ref(wsLocal.getItem(CACHE_KEY.SYSTEM_CONFIG) ? decodeAES(wsLocal.getItem(CACHE_KEY.SYSTEM_CONFIG)) : systemConfigEnum)

  // 获取系统配置缓存
  const getSystemConfigCache = () => {
    if (wsLocal.getItem(CACHE_KEY.SYSTEM_CONFIG)) {
      systemConfig.value = decodeAES(wsLocal.getItem(CACHE_KEY.SYSTEM_CONFIG))
    } else {
      systemConfig.value = systemConfigEnum
      setSystemConfigCache()
    }
    if (systemConfig.value.device === 'mobile') {
      systemConfig.value.layout = 'vertical'
    }
  }

  // 设置系统配置缓存
  const setSystemConfigCache = () => {
    wsLocal.setItem(CACHE_KEY.SYSTEM_CONFIG, encodeAES(systemConfig.value))
  }

  // 设置页面loading状态
  const setPageLoading = (value: boolean) => {
    pageLoading.value = value
  }

  // 获取顶部固钉高度
  const getAffixTop = () => {
    if (systemConfig.value.isFixedHeader) {
      if (systemConfig.value.isFullContent) {
        if (systemConfig.value.isTagEnable) {
          const dom = document.querySelector('.' + variables.namespace + '-layout')
          if (dom) {
            affixTop.value = parseInt(getComputedStyle(dom).getPropertyValue('--el-tag-height')) + systemConfig.value.space + 1
          }
        } else {
          affixTop.value = systemConfig.value.space
        }
      } else {
        const dom = document.querySelector('.' + variables.namespace + '-layout')
        if (dom) {
          if (systemConfig.value.isTagEnable) {
            affixTop.value = parseInt(getComputedStyle(dom).getPropertyValue('--el-header-height')) + parseInt(getComputedStyle(dom).getPropertyValue('--el-tag-height')) + systemConfig.value.space + 1
          } else {
            affixTop.value = parseInt(getComputedStyle(dom).getPropertyValue('--el-header-height')) + systemConfig.value.space
          }
        }
      }
    } else {
      affixTop.value = systemConfig.value.space
    }
  }

  return {
    showSetting,
    affixTop,
    systemConfig,
    pageLoading,
    getSystemConfigCache,
    setSystemConfigCache,
    setPageLoading,
    getAffixTop
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useAppStore, import.meta.hot))
}

export const useAppStoreWithOut = () => {
  return useAppStore(store)
}
